package com.waimai.www.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.protobuf.Timestamp;
import com.waimai.www.po.Caipin;
import com.waimai.www.po.Orders;
import com.waimai.www.po.Users;
import com.waimai.www.service.CaipinService;
import com.waimai.www.service.OrdersService;


@Controller
public class OrdersController {
	@Autowired OrdersService ordersService;
//	获取购物车信息
	@RequestMapping("/orders")
	public class OrdersServlet extends HttpServlet {
		private static final long serialVersionUID = 1L;   
	    public OrdersServlet() {
	        super();
	        // TODO Auto-generated constructor stub
	    }
		protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			// TODO Auto-generated method stub
			CaipinService caipinService = new CaipinService();
			//获取一级物品类型
			try {
				Map<String, String> maps  = caipinService.getAllFirstCaipin();
				//将查询到的一级物品类型保存至request对象中
				request.setAttribute("maps", maps);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//从session取出用户的信息
			Users users = (Users)request.getSession().getAttribute("session_users");
			//将用户信息保存至request对象中
			request.setAttribute("users", users);
			//从购物车中取出物品信息
			Map<Integer,Integer> Shopping_cart = (Map<Integer,Integer>)request.getSession().getAttribute("Shopping_cart");
			List<Caipin> caipinList = new ArrayList<>();
			//总金额
			Double totalPrice = 0.0;
			for(Map.Entry<Integer, Integer> map : Shopping_cart.entrySet()){
				//拿到物品的id
				Integer id = map.getKey();
				//拿到购买的数量
				Integer buyNum = map.getValue();
				
				// 根据物品id查找物品信息
				
				try {
					Caipin caipin = caipinService.getCaipinById(id.toString(), null);
					caipin.setBuyNum(buyNum);
					caipinList.add(caipin);
					totalPrice = totalPrice + caipin.getSmallTotal();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
			}
			//数字格式化类   0.00代表保留两位小数
			DecimalFormat df = new DecimalFormat("0.00");
			//保存总金额
			request.setAttribute("totalPrice", df.format(totalPrice));
			request.setAttribute("caipinList", caipinList);
			//跳转至核对订单信息的页面
			request.getRequestDispatcher("/WEB-INF/jsp/orders.jsp").forward(request, response);
		}
		/**
		 * 保存订单
		 */
		@RequestMapping("/orders")
		public class SaveOrdersServlet extends HttpServlet {
			private static final long serialVersionUID = 1L;
		    public SaveOrdersServlet() {
		        super();
		        // TODO Auto-generated constructor stub
		    }
			protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
				// TODO Auto-generated method stub
				//订单实体
				Orders orders = new Orders();
				//获取订单总金额
				String countMoney = request.getParameter("countMoney");
				orders.setSumprice(Integer.valueOf(countMoney));
				//获取用户信息      假如session已存在则request.getSession()可以取到该session，假如不存在request.getSession(false)会创建一个session  
				Users users = (Users)request.getSession().getAttribute("session_users");
				//保存订单编号   PO+用户id+时间
				StringBuffer sbf = new StringBuffer();
				sbf.append("PO_");
				if(users!=null){
				  //将用户信息保存至订单中
				  orders.setUsers(users);
				  sbf.append(users.getId()+"_");
				}else{
				  //假如用户未登录则跳转至登陆页面，并给出提示信息
				  request.setAttribute("message", "您尚未登录系统，请求登录后再结算订单！");   
				}
				orders.setZhifutime((java.sql.Timestamp) new java.util.Date());
				SimpleDateFormat  dateFormat = new  SimpleDateFormat ("yyyyMMddHHmmss");
				String date = dateFormat.format(new Date());
				System.out.println("date:"+date);
				sbf.append(date);
				System.out.println("订单编号："+sbf.toString());
				//将订单编号保存至orders中
				orders.setOrderid(sbf.toString());
				/**************************************获取订单明细***************************************/
				//用于存放订单明细
				List<Orders> ordersList = new ArrayList<Orders>();
				//从session中取出购物车
				@SuppressWarnings("unchecked")
				Map<Integer,Integer>  Shopping_cart= (Map<Integer,Integer>)request.getSession().getAttribute("Shopping_cart");
				for(Map.Entry<Integer, Integer> map : Shopping_cart.entrySet()){
					//创建订单明细表
					//获取物品id
					Integer caipinId = map.getKey();
					//获取物品数量
					Integer number = map.getValue();
					Integer fname = Integer.parseInt("fname");
					orders.setFname(fname);
					orders.setOrdercount(number);
					ordersList.add(orders);
				}
				OrdersService ordersService = new OrdersService();
				//调用订单服务层方法保存订单以及订单信息
				try {
					ordersService.saveOrdersAndOrders(orders,ordersList);
					//跳转至展示订单数据的Servlet
					response.sendRedirect(request.getContextPath()+"/orders.action");
				 } catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}

		}
		/**
		 * 展示订单列表
		 */
		@RequestMapping("/orders")
		public class OrdersListServlet extends HttpServlet {
			private static final long serialVersionUID = 1L;   
		    /**
		     * @see HttpServlet#HttpServlet()
		     */
		    public OrdersListServlet() {
		        super();
		        // TODO Auto-generated constructor stub
		    }
			/**
			 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
			 */
			protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
				// TODO Auto-generated method stub
				this.doPost(request, response);
			}
			/**
			 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
			 */
			protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
				// TODO Auto-generated method stub
				OrdersService ordersService = new OrdersService();
				//清空购物车中的数据
				request.getSession().removeAttribute("Shopping_cart");
				//获取当前用户的所有订单信息
				Users users = (Users)request.getSession().getAttribute("session_users");
				if(users==null){
					//如果为空则跳转至登陆页面
					request.setAttribute("message", "您尚未登录系统，请登陆后再查看订单信息！");
					request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
				}else{
					Integer usersId = users.getId();
					System.out.println("用户id："+usersId);
					try {
						//根据用户id获取用户订单信息
						List<Orders> ordersList = ordersService.getAllOrdersByUsersId(usersId);
						//取出订单中物品信息
						for(int i=0;i<ordersList.size();i++){
							Integer ordersId = ordersList.get(i).getOrderid();
							System.out.println("订单id："+ordersId);
							//根据订单获取订单明细
							List<Orders> ordersLlist = ordersService.getOrdersById(ordersId);
							//将订单明细存放订单对象中
							ordersList.get(i).setOrderss(ordersLlist);
						}		
						request.setAttribute("ordersList", ordersList);
						//保存订单数量
						request.setAttribute("size", ordersList.size());
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						request.setAttribute("message", "查询订单数据出现异常："+e.getMessage());
					}
					//跳转至订单列表页面
				  request.getRequestDispatcher("/WEB-INF/jsp/orders.jsp").forward(request, response);
				}
			}
		}
	}
}
